package com.zeng.sim.support.protocol;

import com.zeng.sim.controller.domain.msg.MsgData;
import com.zeng.sim.util.SimConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-12-25T15:33
 */
@Component
public class SocketMsgProtocol implements IMsgProtocol {

    private Logger logger = LoggerFactory.getLogger(SocketMsgProtocol.class);

    /**
     * 是否支持
     * @param msgProtocol
     * @return
     */
    @Override
    public boolean support(SimConstant.MsgProtocol msgProtocol) {
        return SimConstant.MsgProtocol.MSG_PROTOCOL_SOCKET.equals(msgProtocol);
    }

    /**
     * 发送消息
     * @param msgData
     * @return 响应报文
     */
    @Override
    public String sendMsg(MsgData msgData) {
        Socket socket = null;
        try {
            logger.info("客户端发起请求，hostname[{}]，port[{}]", msgData.getHostname(), msgData.getPort());
            socket = new Socket(msgData.getHostname(), msgData.getPort());
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(60));

            // 发送请求报文
            logger.info("发送请求报文[{}]", msgData.getMsgContent());
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(msgData.getMsgContent().getBytes(msgData.getCharsetName()));
            outputStream.flush();
            socket.shutdownOutput();

            // 接收响应报文
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = inputStream.read(buf)) != -1) {
                byteStream.write(buf, 0, len);
            }
            inputStream.close();

            String respMsg = byteStream.toString(msgData.getCharsetName());
            logger.info("收到响应报文[{}]", respMsg);
            return respMsg;

        }
        catch (IOException e) {
            throw new IllegalStateException("发送消息失败，" + e.getMessage(), e);
        }
        finally {
            if (socket != null) {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    logger.warn("关闭Socket连接失败，" + e.getMessage(), e);
                }
            }
        }
    }

}
